/*
Window handling from Nate Robis' Tutorial
*/

#include "natewin.h"


GLvoid *font_style = GLUT_BITMAP_TIMES_ROMAN_10;
GLint selection = 0;

GLint getSelection() { return selection; }
void  setSelection(GLint _selection) { selection = _selection; }

void setfont(char* name, int size) {
	font_style = GLUT_BITMAP_HELVETICA_10;
	if (strcmp(name, "helvetica") == 0) {
		if (size == 12) 
			font_style = GLUT_BITMAP_HELVETICA_12;
		else if (size == 18)
			font_style = GLUT_BITMAP_HELVETICA_18;
	} else if (strcmp(name, "times roman") == 0) {
		font_style = GLUT_BITMAP_TIMES_ROMAN_10;
		if (size == 24)
			font_style = GLUT_BITMAP_TIMES_ROMAN_24;
	} else if (strcmp(name, "8x13") == 0) {
		font_style = GLUT_BITMAP_8_BY_13;
	} else if (strcmp(name, "9x15") == 0) {
		font_style = GLUT_BITMAP_9_BY_15;
	}
}

void drawstr(GLuint x, GLuint y, char* format, ...) {
	va_list args;
	char buffer[255], *s;

	va_start(args, format);
	vsprintf(buffer, format, args);
	va_end(args);

	glRasterPos2i(x, y);
	for (s = buffer; *s; s++)
		glutBitmapCharacter(font_style, *s);
}

void cell_draw(cell* cell) {
	glColor3ub(0, 255, 128);
	if (selection == cell->id) {
		glColor3ub(255, 255, 0);
		drawstr(10, 240, cell->info);
		glColor3ub(255, 0, 0);
	}

	drawstr(cell->x, cell->y, cell->format, cell->value);
}

int cell_hit(cell* cell, int x, int y) {
	if (x > cell->x && x < cell->x + 60 &&
		y > cell->y-30 && y < cell->y+10)
		return cell->id;
	return 0;
}

void cell_update(cell* cell, int update) {
	if (selection != cell->id)
		return;

	cell->value += update * cell->step;

	if (cell->value < cell->min)
		cell->value = cell->min;
	else if (cell->value > cell->max) 
		cell->value = cell->max;

}

void cell_vector(float* dst, cell* cell, int num) {
	while (--num >= 0)
		dst[num] = cell[num].value;
}